/**
* 作者:ZHX
* 日期:2024/5/17
* 描述:登录
*/

<template>
  <div class="Login">
    <div class="box-center">
      <div class="top-text"><h3>欢迎使用</h3></div>
      <div style="display: flex;height: 50px;margin-top: -10px">
        <el-button :style="{fontWeight:BtnStatus?900:100}" :type="BtnStatus?'danger':''" class="Btn" text
                   @click="BtnStatus=true">手机号登录
        </el-button>
        <el-button :style="{fontWeight:BtnStatus?100:900}" :type="BtnStatus?'':'danger'" class="Btn" text
                   @click="BtnStatus=false">用户名登录
        </el-button>
      </div>
      <el-form ref="LoginFrom" :hide-required-asterisk="true" :model="from" :rules="rules" class="demo-ruleForm"
               label-position="top">
        <el-form-item v-if="BtnStatus" label="手机号" prop="cellphone">
          <el-input v-model="from.cellphone" autocomplete="off" clearable placeholder="请输入手机号"
                    prefix-icon="Iphone"
                    type="text" @keyup.enter.native="Login"></el-input>
        </el-form-item>
        <el-form-item v-if="!BtnStatus" label="用户名称" prop="username">
          <el-input v-model="from.username" autocomplete="off" clearable placeholder="请输入用户名"
                    prefix-icon="UserFilled"
                    type="text" @keyup.enter.native="Login"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="用户密码">
          <el-input v-model="from.password" autocomplete="off" clearable placeholder="请输入密码"
                    prefix-icon="Lock" show-password type="password" @keyup.enter.native="Login"></el-input>
        </el-form-item>
        <el-form-item prop="verifyCode" label="验证码">
          <el-row>
            <el-col :span="16">
              <el-input v-model="from.verifyCode" autocomplete="off" clearable placeholder="验证码--点击图片刷新"
                        prefix-icon="Orange" type="text" @keyup.enter.native="Login"></el-input>
            </el-col>
            <el-col :span="8" class="">
              <div @click="initCode" style="height: 40px; margin-left: 15px">
                <img v-if="!imgCode" src="@/assets/img/login/404.jpg"
                     style="width: 100%; height: 100%; cursor: pointer"/>
                <img v-else :src="imgCode" style="width: 100%; height: 100%; cursor: pointer"/>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <div class="box-bom">
          <el-button size="default" type="primary" @click="Login">登 录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import md5 from "js-md5";
import {mySession, myStorage} from "@/utils/localStorage/index";
import {localStorageList} from '@/utils/Menu/menu.js'
import {setMessageCallback, publishMsg, removeMessageCallback} from "@/mqtt";
import {Base64} from 'js-base64';
import {ElMessage} from "element-plus";
import {onBeforeUnmount, reactive, onMounted, toRefs} from "vue";
import {useRouter} from "vue-router";
import {SCADA_MSG} from "@/utils/Menu/menu.js";

export default {
  name: "Login",
  setup() {
    const router = useRouter()
    const data = reactive({
      from: {
        cellphone: "",
        username: "",
        password: "",
        verifyCode: "",
      },
      imgCode: "",
      LoginFrom: null,
      BtnStatus: true,
      // 表单验证
      rules: {
        cellphone: [
          {required: true, message: '请输入手机号', trigger: 'change'},//验证手机
          {validator: validateTel, trigger: 'blur'}
        ],
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
        ],
        password: [
          {required: true, message: "请输入用户密码", trigger: "blur"},
          {min: 1,/* max: 11, */ message: "密码不能为空", trigger: "blur",},
        ],
        verifyCode: [
          {required: true, message: "请输入验证码", trigger: "blur"},
          {min: 4, message: "长度最小4个字符", trigger: "blur",},
        ],
      },
    })
    onMounted(() => {
      setTimeout(() => {
        setMessageCallback(onMessage);
        initCode();
      }, 200);
    })
    onBeforeUnmount(() => {
      removeMessageCallback(onMessage);
    })
    const reset = () => {
      data.LoginFrom.resetFields();
    }
    const Login = () => {
      data.LoginFrom.validate(async (vail) => {
        if (!vail) {
          return false;
        }
        //将密码进行三次加密
        for (let i = 0; i < 3; i++) {
          data.from.password = md5(data.from.password);
        }
        //将最终密码解密
        data.from.password = Base64.encode(data.from.password);
        let msg = {
          webMsgType: SCADA_MSG.scada_login,
          funCode: data.BtnStatus ? 1 : 0,
          clientId: myStorage.get('clientId'),
        };
        let newMsg = {...msg, data: data.from};
        if (data.BtnStatus) {
          delete newMsg.data.username
        } else {
          delete newMsg.data.cellphone
        }
        publishMsg(newMsg);
      });
    }
    const onMessage = (topic, msg) => {
      switch (msg.webMsgType) {
        case SCADA_MSG.scada_captha:
          switch (msg.retCode) {
            case 0:
              data.imgCode = msg.data.captchaImg;
              break;
            case 1:
              router.push("/Home");
              ElMessage.info(msg.retMsg);
              break;
            default:
              break;
          }
          break;
        case SCADA_MSG.scada_login:
          switch (msg.retCode) {
            case 0:
              getParamSystem();
              myStorage.set("activePath", '/Home');
              router.push("/Home");
              ElMessage.success("登录成功！");
              break;
            case 1:
            case 2:
              reset();
              ElMessage.error(msg.retMsg);
              break;
            case 3:
              data.from.verifyCode = "";
              ElMessage.error(msg.retMsg);
              initCode();
              break;
            case 4:
              data.from.password = "";
              ElMessage.error(msg.retMsg);
              break;
            case 5:
              data.from.username = "";
              ElMessage.error(msg.retMsg);
              break;
            case 6:
              data.from.cellphone = "";
              ElMessage.error(msg.retMsg);
              break;
            default:
              reset();
              break;
          }
          break;
        default:
          break;
      }
    }
    const initCode = () => {
      // 判断浏览器是否上网
      if (navigator.onLine) {
        let sendMsg = {webMsgType: SCADA_MSG.scada_captha, funCode: 0,};
        publishMsg(sendMsg);
      }
    }
    const getParamSystem = () => {
      publishMsg({webMsgType: SCADA_MSG.scada_param_system, funCode: 0,});
    }

    function validateTel(rule, value, callback) {
      const regexp = /^(\+\d{2,3}-)?\d{11}$/;
      if (!regexp.test(value)) {
        callback(new Error("请输入正确的号码格式"));
      } else {
        callback();
      }
    }
    return ({
      ...toRefs(data),
      reset, onMessage, initCode, Login, getParamSystem
    })
  },
};
</script>
<style scoped lang="scss">
.custom-tabs-label {
  display: flex;
  align-items: center
}

.Btn {
  width: 50%;
  font-size: 18px;
  margin-left: 0;
}

.Login {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  justify-content: space-between;
  background-image: url("@/assets/img/login/bj.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center bottom;

  .box-center {
    background-color: #fff;
    width: 400px;
    // height: 430px;
    margin: 0px auto;
    border-radius: 10px;
    position: fixed;
    top: 50%;
    left: 70%;
    transform: translateX(-50%) translateY(-50%);
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.2);

    .demo-ruleForm {
      padding: 0px 50px 30px 50px;
    }

    .top-text {
      flex: 1;

      h3 {
        font-size: 26px;
        text-align: center;
      }
    }
  }

  .box-bom {
    // height: 40px;
    .el-button {
      width: 100%;
      height: 40px;
    }
  }
}

::v-deep .el-form-item__label {
  padding: 0px;
}

::v-deep .el-form-item__content {
  line-height: 40px;
}

::v-deep .el-input__inner {
  background-color: #f7f8fc;
  height: 40px;
  line-height: 40px;
  padding-left: 0;
}

::v-deep .el-input__icon {
  line-height: 0px;
}

::v-deep .el-col {
  height: 40px;
}

::v-deep .el-input__wrapper {
  background-color: #f7f8fc;
}
</style>
